<template>
  <view :class="$style.container">

    <map id="mapId" class="map" style="width: 100%;height:100%;" :latitude="currentLatitude"
      :longitude="currentLongitude" show-location="true" :markers="markers" :circles="circles" :polyline="polyline"
      scale="14"></map>

    <!-- 警情概览信息展示  -->
    <alarm-info :ajxxId="jqId" :fixBottom="alarmFixBottom"></alarm-info>

    <!-- 收藏 查看详情操作 盒子高度 76rpx -->
    <view :class="$style.info" class="flex absolute justify-evenly" :style="{ 'bottom': operationFixBottom }">
      <view class="flex items-center" :class="$style.option" @click="handleFavoriteClick">
        <!-- 未收藏 -->
        <image :src="favoriteImg" mode="widthFix" style="width:32rpx; height: 32rpx;" v-show="!isFavorite"></image>
        <!-- 已收藏 -->
        <image :src="isFavoriteImg" mode="widthFix" style="width:32rpx; height: 32rpx;" v-show="isFavorite"></image>
        <view :class="$style.text">收藏</view>
      </view>
      <view class="flex-col-center" :class="$style.divider"></view>
      <view :class="$style.detail" class="flex items-center" @click="openAlertDetailPage">
        <image :src="detailImg" mode="widthFix" style="width:32rpx"></image>
        <view :class="$style.text">详情</view>
      </view>
    </view>

    <!-- 底部 调派 确认收到操作  高度 144rpx -->
    <view :class="$style.operation" class="flex absolute items-center" style="width:100%; bottom: 0%;"
      v-if="operationShowFlag">

      <button :class="$style.button" v-if="!isReadyDispatch" @click="handleSpectatorClick">观战</button>
      <button :class="$style.button" v-else @click="handleDispatchPeople">派人去</button>

      <!-- isReadyDispatch 出动状态判断 -->
      <receive-verify class="flex-1" style="margin: 0 30rpx" v-if="!isReadyDispatch"
        @changeDispatchState="changeDispatchState"></receive-verify>
      <button :class="$style.dispatch" class="flex-1" style="margin: 0 30rpx" v-else
        @click="handleDispatchClick">立即出动</button>

      <van-dialog use-slot :show="dialogShowFlag" show-cancel-button @cancel="openFirefightPage"
        @confirm="openThirdPartyMap" @close="onCloseDialog">
        <view :class="$style.dialog" class="flex items-center justify-center">
          <view :class="$style.text">是否跳转至手机APP进行导航？</view>
          <image :src="STATIC_URL + '/img/dialog1537643688212037632.png'" mode="widthFix" style="width: 150rpx;">
          </image>
        </view>
      </van-dialog>
    </view>
    <!-- 重要通知 -->
    <!-- 先隐藏通知图标，下个版本添加 -->
    <!-- <view :class="$style.notice_bar" class="absolute">
      <van-icon :name="noticeImg" :info="noticeNumber" @click="openNoticePopup" size="48rpx"></van-icon>
    </view> -->

    <view :class="$style.confirm_arrive" class="absolute flex-col-center" @click="reportFightState(2)"
      v-if="!operationShowFlag && isReadyDispatch && arrivalState">
      <view :class="$style.text">确认到场</view>
    </view>

    <!-- 右侧固定栏  媒体功能模块  -->
    <view class="absolute" style="bottom: 0; width: 100%">
      <media-function :isFeedbackShow="true" v-show="!operationShowFlag" :jqId="jqId"></media-function>
    </view>
    <!-- 右侧固定栏  地图交互模块  -->
    <map-interaction v-show="!operationShowFlag && false"></map-interaction>
  </view>
</template>

<script setup lang='ts'>
import { ref, onMounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { STATIC_URL } from '@/config'
import {
  insertJsdp, queryWhetherCollectAlert, insertCollectAlert, queryAlertInfo,
  queryClGps, queryRyGps, queryQsmt, queryRgsy,
  queryTrsy, queryXhs, queryJcXfjgFwInfo, insertCzryxx
} from '@/api'
import { useInstantMessage, useLocationInfo } from '@/store'
import { getLocal } from "@/utils";
import AlarmInfo from "@/components/alarm-info/index.vue";
import ReceiveVerify from "@/components/receive-verify/index.vue";
import MediaFunction from "@/components/media-function/index.vue";
import MapInteraction from "@/components/map-interaction/index.vue";

import favoriteImg from "@/static/images/common/favorite.png";
import isFavoriteImg from "@/static/images/common/isFavorite.png";
import detailImg from "@/static/images/receive-assign/detail.png";

import noticeImg from "@/static/images/receive-assign/notice.png";


type MarkerType = {
  id: number;
  latitude: number;
  longitude: number;
  iconPath: string;
  callout: object;
  width: number;
  height: number;
};

onLoad((option) => {
  console.log("跳转至警情调派页面时携带的参数", option);
  jqId.value = option.jqId
  lxMc.value = option.lxMc
})

// 获取当前位置信息
const currentLocation = useLocationInfo().getLocationInfo;
const currentLatitude = ref<number>(currentLocation.latitude);
const currentLongitude = ref<number>(currentLocation.longitude);

// 根据短信打开小程序 携带的参数  警情id、警情类型名称
const jqId = ref<string | undefined>("");
const lxMc = ref<string | undefined>("");

// 调派,收藏,调派人员,通知框 标记
const isReadyDispatch = ref<boolean>(false);
const isFavorite = ref<boolean>(false);
const dialogShowFlag = ref<boolean>(false);
const arrivalState = ref<boolean>(true);

// 重要通知
let noticeNumber = ref<number>(10);

// 警情盒子和收藏操作 初始位置：立即出动操作之后 进行模块位置 调整
const alarmFixBottom = ref<number | string>('240rpx')
const operationFixBottom = ref<string>('154rpx')
const operationShowFlag = ref<boolean>(true)
/**
 * 获取账号信息 openid
 */
let openid = getLocal('openid')
let lqryInfo: any = getLocal('lqryInfo')
const chatStore = useInstantMessage()
const markers = ref<Array<MarkerType>>([
  {
    id: 1,
    latitude: 0,
    longitude: 0,
    width: 40,
    height: 40,
    iconPath: "../../static/location.png",
    callout: {
      content: "终点",
      color: "#ff0000",
      fontSize: 14,
      borderWidth: 2,
      borderRadius: 10,
      borderColor: "#000000",
      bgColor: "#ffffff",
      padding: 5,
      display: "ALWAYS",
      textAlign: "center",
    },
  },
]);
const circles = ref<any>()
const polyline = ref<any>()

function getList() {
  queryAlertInfo({ ajxxId: jqId.value })
    .then((res: any) => {
      console.log('chancel', 'index', '158行', res);
      // 地图焦点
      currentLatitude.value = res.data.wd
      currentLongitude.value = res.data.jd
      // 终点
      markers.value[0].latitude = res.data.wd
      markers.value[0].longitude = res.data.jd
      // console.log('chancel', 'index', '164行', markers.value[0].callout.content);
      // markers.value[0].callout.content = res.data.afdz
      // 设置圈
      circles.value = [{
        latitude: res.data.wd,
        longitude: res.data.jd,
        color: "#3E60DC",
        radius: 200,
        strokeWidth: 2,
        fillColor: "#637ee136"
      }]
      // 设置路径
      polyline.value = [
        {
          points: [
            {
              latitude: res.data.wd,
              longitude: res.data.jd,
            },
            {
              latitude: res.data.wd + 0.0004,
              longitude: res.data.jd + 0.0004,
            },
            {
              latitude: res.data.wd + 0.001,
              longitude: res.data.jd + 0.002,
            }
          ],
          color: "#66b3fe",
          borderColor: "#3E60DC",
          width: 10
        }
      ]
      // queryAllInfo()
    })
    .catch((e: any) => {
      console.log(e);
    });
}

/** 打开 重要通知 消息提示框 */
function openNoticePopup() {
  console.log("打开消息通知栏");
  uni.navigateTo({ url: '/pages/assign-module/vertical-message/index' });
}

/**
 * 确认收到调派 切换到 立即出动 按钮
 * @param val {number}
 */
function changeDispatchState() {
  console.log("收到调派");
  isReadyDispatch.value = true;
  // confirmReceiveAssign()
}
/**
 * 调用 接收调派接口（收到按钮）
 * 缺少 dppc jqid 字段（调派批次 警情id 账号主体）
 */
function confirmReceiveAssign() {
  let params: object = {
    dppc: 1,
    jqid: jqId.value,
    sfSjr: 1,
    yjlddwBm: lqryInfo.yjlddwTywysbm,
    zgjgbh: lqryInfo.xfjyjgTywysbm,
    zhid: openid,
    zhzt: lqryInfo.yjlddwlxdm
  }
  insertJsdp(params).then((res: any) => {
    console.log('加入群聊', res);
    // 将 群组 code 存入 store 中
    chatStore.setChatGroup(res.data)
  }).catch((e: any) => {
    console.log(e);
  })
}
/** 处理警情收藏 按钮点击事件 */
function handleFavoriteClick() {

  console.log("收藏状态", isFavorite.value);
  let state = 0
  // 已经收藏
  if (isFavorite.value) {
    // TODO 取消收藏
    state = 0
  } else {
    // TODO 添加收藏
    state = 1
  }
  insertCollectAlert({ jqId: jqId.value, sfjrsc: state, zhId: openid })
    .then((res: any) => {
      if (res.result.resultCode == "000000") {
        isFavorite.value = !isFavorite.value;
      }
    })
    .catch((e: any) => {
      console.log(e);
    });
}

/** 警情详情页面点击 打开警情详情页面 */
function openAlertDetailPage() {
  console.log("打开警情详情页面");
  uni.navigateTo({
    url: "/pages/alarm-overview/index?jqId=" + jqId.value + '&alertCard=true',
  });
}

/** 处理观战 按钮点击事件 */
function handleSpectatorClick() {
  console.log("直接进入");
  uni.navigateTo({ url: "/pages/alarm-overview/index?jqId=" + jqId.value + '&alertCard=false', })
}

/** 处理派人去 按钮点击事件 */
function handleDispatchPeople() {
  console.log("派人去");
  uni.navigateTo({ url: '/pages/assign-module/contact-list/index?jqId=' + jqId.value + + '&lxMc=' + lxMc.value })
}

/** 处理立即战斗 按钮点击事件 */
function handleDispatchClick() {
  console.log("立即加入战斗");
  reportFightState(1)
  // 打开 导航确认提示框
  dialogShowFlag.value = true;
}
/** 取消导航 直接打开战斗页面 */
function openFirefightPage() {
  changeModulePosition()
  operationShowFlag.value = false
}

/*** 关闭弹窗时置为false */
function onCloseDialog() {
  dialogShowFlag.value = false;
}

function changeModulePosition() {
  alarmFixBottom.value = '200rpx'
  operationFixBottom.value = '114rpx'
}

/**
 * 上报作战状态 1：出动 2: 到场
 */
function reportFightState(state: number | string) {
  let params: any = {
    czlx: state,
    dppc: 1,
    jqId: jqId.value,
    sfSjr: 1,
    sjrZhid: openid, // 首接人账号 默认以 当前账号id 
    yjlddwBm: lqryInfo.yjlddwTywysbm,
    zgjgbh: lqryInfo.xfjyjgTywysbm,
    zhId: openid,
    zhzt: lqryInfo.yjlddwlxdm,
  }
  insertCzryxx(params).then((res: any) => {
    console.log('上报战斗状态:', state === 2 ? '确认到场' : '立即出动', res);
    if (res.result.resultCode === "000000") {
      arrivalState.value = false
      chatStore.setChatGroup(res?.data)
    }

  }).catch((e: any) => {
    console.log('上报出错', e);
  })
}

/**
 * 打开第三方地图
 */
function openThirdPartyMap() {
  // 需要将底部操作模块隐藏，并将警情信息模块和 收藏模块下移
  changeModulePosition()
  operationShowFlag.value = false

  uni.openLocation({
    latitude: currentLatitude.value,
    longitude: currentLongitude.value,
    name: '新街口',
    address: '秦淮区新街口正洪街',
    success: function () {
      dialogShowFlag.value = false;
      console.log("success");
    },
  });
}

/** 页面挂载时 获取数据 */
onMounted(() => {
  // 获取是否收藏数据
  collectAlert(jqId.value)
  // 获取警情信息
  getList()
})

// 获取警情范围 周边信息
function queryAllInfo() {
  console.log('chancel', 'index', '379行', 11111);
  // 获取车辆
  queryClGpsFunc()
  // 获取人员
  queryRyGpsFunc()
  // 获取取水码头
  queryQsmtFunc()
  // 获取人工水源
  queryRgsyFunc()
  // 获取天然水源
  queryTrsyFunc()
  // 获取消火栓
  queryXhsFunc()
  // 获取队站
  queryJcXfjgFwInfoFunc()
}
// 获取车辆
function queryClGpsFunc() {
  queryClGps({ ajxxId: 202205250525, cxfw: 5000 }).then((res: any) => {
    if (res.result.resultCode == "000000") {
      markers.value = setMarkers(res)
    }
  })
    .catch((e: any) => {
      console.log(e);
    });
}
// 获取人员
function queryRyGpsFunc() {
  queryRyGps({ ajxxId: 202205250525, bj: 5000, zhId: openid }).then((res: any) => {
    if (res.result.resultCode == "000000") {
      markers.value = setMarkers(res)
    }
  })
    .catch((e: any) => {
      console.log(e);
    });
}
// 获取取水码头
function queryQsmtFunc() {
  queryQsmt({ wd: currentLatitude.value, jd: currentLongitude.value, xcfw: 5000 }).then((res: any) => {
    if (res.result.resultCode == "000000") {
      markers.value = setMarkers(res)
    }
  })
    .catch((e: any) => {
      console.log(e);
    });
}
// 获取人工水源
function queryRgsyFunc() {
  queryRgsy({ wd: currentLatitude.value, jd: currentLongitude.value, xcfw: 5000 }).then((res: any) => {
    if (res.result.resultCode == "000000") {
      markers.value = setMarkers(res)
    }
  })
    .catch((e: any) => {
      console.log(e);
    });
}
// 获取天然水源
function queryTrsyFunc() {
  queryTrsy({ wd: currentLatitude.value, jd: currentLongitude.value, xcfw: 5000 }).then((res: any) => {
    if (res.result.resultCode == "000000") {
      markers.value = setMarkers(res)
    }
  })
    .catch((e: any) => {
      console.log(e);
    });
}
// 获取消火栓
function queryXhsFunc() {
  queryXhs({ wd: currentLatitude.value, jd: currentLongitude.value, xcfw: 5000 }).then((res: any) => {
    if (res.result.resultCode == "000000") {
      markers.value = setMarkers(res)
    }
  })
    .catch((e: any) => {
      console.log(e);
    });
}
// 获取队站
function queryJcXfjgFwInfoFunc() {
  queryJcXfjgFwInfo({ wd: currentLatitude.value, jd: currentLongitude.value, bj: 5000 }).then((res: any) => {
    if (res.result.resultCode == "000000") {
      markers.value = setMarkers(res)
    }
  })
    .catch((e: any) => {
      console.log(e);
    });
}

let a = 0

// 数组塞进markers
function setMarkers(res: any) {
  a = a + 1
  return [
    ...markers.value,
    ...res.data && res.data.map((item: any, index: any) => {
      return {
        id: item.location.lat,
        latitude: item.location.lat,
        longitude: item.location.lon,
        width: 40,
        height: 40,
        iconPath: item.tblj,
      }
    }) || []
  ]

}

// 查询收藏信息
function collectAlert(jqId: string | undefined) {
  let params = {
    ajxxId: jqId,
    zhid: openid
  }
  queryWhetherCollectAlert(params).then((res: any) => {
    console.log('当前账户人员是否收藏警情', res.data);
    if (res.result.resultCode === '000000') {
      isFavorite.value = res.data
    }
  }).catch((e: any) => {
    console.log('查询收藏警情出错', e);

  })
}
</script>

<style lang='less' module>
.container {
  position: relative;
  width: 100vw;
  height: 100vh;

  .notice_bar {
    left: 30rpx;
    bottom: 40%;
  }

  .info {
    left: 30rpx;
    width: calc(100% - 60rpx);
    height: 76rpx;
    background: #ffffff;
    box-shadow: 0px 4px 19px 1px rgba(51, 51, 51, 0.2);
    border-radius: 20px;

    .divider {
      height: calc(100% - 20rpx);
      margin-top: 10rpx;
      border-right: 1px solid #e8e8e8;
    }

    .text {
      font-size: 24rpx;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #333333;
      margin-left: 10rpx;
    }
  }

  .operation {
    height: 144rpx;
    background: #ffffff;
    box-shadow: 0px 4px 19px 1px rgba(51, 51, 51, 0.2);

    .button {
      width: 220rpx;
      height: 80rpx;
      background: rgba(86, 120, 244, 0.1);
      border-radius: 40rpx;
      font-size: 30rpx;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #5678f4;
      margin-left: 30rpx;

      &::after {
        border: 0;
      }
    }

    .dispatch {
      background-image: linear-gradient(to right, #4520ca, #c90842);
      height: 80rpx;
      width: 100%;
      color: #ffffff;
      border-radius: 40rpx;
      font-size: 30rpx;
    }
  }

  .dialog {
    // width: 544rpx;
    height: 260rpx;
    background: #ffffff;
    border-radius: 16px;

    .text {
      width: 290rpx;
      font-size: 32rpx;
      font-family: Microsoft YaHei;
      font-weight: bold;
      color: #375ce4;
    }
  }

  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .block {
    width: 120px;
    height: 120px;
    background-color: #fff;
  }

  .confirm_arrive {
    right: 20rpx;
    top: 670rpx;
    width: 150rpx;
    height: 150rpx;
    border-radius: 50%;
    background-image: linear-gradient(to bottom right, #307bdf, #df0428);

    .text {
      width: 66rpx;
      font-size: 32rpx;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #FFFFFF;
    }
  }
}
</style>
